﻿using System;
using Castle.Core;
using Mbs.CastleContainer.Facilities;

namespace Mbs.CastleContainer
{
    /// <summary>
    /// 方法注入装备
    /// </summary>
    public class StartableFacility : MbsFacility
    {
        private static readonly Type StartableType = typeof(Mbs.IStartable);
        private static readonly Type InitType = typeof(Mbs.IInitializable);
        private static readonly Type CastleStartableType = typeof(Castle.Core.IStartable);

        public StartableFacility() : base(KernelListnerType.ComponentModelCreated) { }
         
        public override void OnComponentModelCreated(Castle.Core.ComponentModel model)
        {
            if (model.Configuration == null)
                return;

            if (StartableType.IsAssignableFrom(model.Implementation)
                ||InitType.IsAssignableFrom(model.Implementation)
                ||CastleStartableType.IsAssignableFrom(model.Implementation)
                || !string.IsNullOrEmpty(model.Configuration.Attributes["startMethod"])
                || !string.IsNullOrEmpty(model.Configuration.Attributes["stopMethod"]))
                InitLifecycleSteps(model);
        }

        private static void InitLifecycleSteps(Castle.Core.ComponentModel model)
        {
            model.LifecycleSteps.Add(
                LifecycleStepType.Commission, StartConcern.Instance);
            model.LifecycleSteps.AddFirst(
                LifecycleStepType.Decommission, StopConcern.Instance);
        }
    }
}
